package com.yand.oratransmysql.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


/**
 * @author yanzz
 *    数据源配置类
 */
@Configuration
@MapperScan(sqlSessionFactoryRef = "SqlSessionFactory",basePackages = "com.yand.oratransmysql.mapper")
public class DataSourceConfig {


    /**
     * 添加 oracle 数据库注解
     * @return
     */
    @Bean(name = "oracleDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    public DataSource getDateSourceOracle() {

        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 添加 mysql 数据库注解
     * @return
     */
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db2")
    public DataSource getDateSourceMysql() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 数据源切换: 通过AOP在不同数据源之间动态切换
     */
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource() {

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //设置默认数据源，默认数据源为oracle
        dynamicDataSource.setDefaultTargetDataSource(getDateSourceOracle());
        //配置多数据源
        Map<Object, Object> dsMap = new HashMap<>(2);
        dsMap.put(DataSourceName.ORACLE, getDateSourceOracle());
        dsMap.put(DataSourceName.MYSQL,  getDateSourceMysql());
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }

    @Bean(name = "SqlSessionFactory")
    public SqlSessionFactory arraignSqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath*:mapper/*Mapper.xml"));
        return bean.getObject();
    }


}